<template>
    <div class="live-course-list">
      <el-card>
        <div class="header">
          <h2>直播课管理</h2>
          <el-button type="primary" @click="showCreateDialog = true">
            创建直播课
          </el-button>
        </div>
  
        <el-table :data="courses" style="width: 100%" border>
          <el-table-column prop="channelName" label="课程名称" />
          <el-table-column prop="startTime" label="开始时间" />
          <el-table-column label="操作" width="240">
            <template #default="scope">
              <el-button size="small" @click="editCourse(scope.$index)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteCourse(scope.$index)">删除</el-button>
              <el-button size="small" type="success" @click="enterLiveRoom(scope.row.id)">进入直播</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 创建直播课对话框 -->
      <el-dialog title="创建直播课" v-model="showCreateDialog" width="400px">
        <el-form :model="newCourse" :rules="rules" ref="createForm">
          <el-form-item label="课程名称" prop="title">
            <el-input v-model="newCourse.title" placeholder="请输入课程名称" />
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="newCourse.startTime"
              type="datetime"
              placeholder="选择开始时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="createCourse">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref,onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useRouter } from 'vue-router'
  import request from '@/utils/request.js'
  import { parseJwt } from '@/utils/jwt'
  import { useUserStore } from '@/stores/user'
  import dayjs from 'dayjs'
  const userStore = useUserStore()
const router = useRouter()
  
  // 直播课数据示例
  const courses = ref([
  ])
  
  // 创建对话框控制
  const showCreateDialog = ref(false)
  
  // 新建直播课表单数据
  const newCourse = ref({
    title: '',
    startTime: ''
  })
  
  // 表单验证规则
  const rules = {
    title: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }]
  }
  
  // 表单引用
  const createForm = ref(null)
  
  // 编辑直播课（这里简单示例，可扩展）
  const editCourse = (index) => {
    ElMessage.info(`编辑直播课：${courses.value[index].title}`)
  }
  
  // 删除直播课
  const deleteCourse = async (index) => {
    try {
      await ElMessageBox.confirm(`确定删除直播课《${courses.value[index].title}》吗？`, '确认删除', {
        type: 'warning'
      })
      courses.value.splice(index, 1)
      ElMessage.success('删除成功')
    } catch {
      ElMessage.info('已取消删除')
    }
  }
  
  const enterLiveRoom = async (channelId) => {
  const token = userStore.token
  const userId = parseJwt(token).sub

  // 直接从courses里找对应直播课
  const targetCourse = courses.value.find(c => c.id === channelId)

  if (!targetCourse) {
    ElMessage.error('直播间不存在')
    return
  }

  const hostId = targetCourse.userId
  console.log(hostId)

  try {
    // 进入直播间获取临时 token
    const res = await request.post('/rtc/enter', null, {
      params: { userId, channelId }
    })

    if (res.code === 200) {
      const liveToken = res.data
      const query = {
        uid: userId,
        token: liveToken,
        hostId,
        userName: (userId === hostId ? '主播' : '访客') + userId.slice(-3)
      }
      router.push({
        name: 'LiveRoom',
        params: { id: channelId },
        query
      })
    } else {
      ElMessage.error(res.message || '进入直播间失败')
    }
  } catch (e) {
    ElMessage.error('进入直播间异常')
    console.error(e)
  }
}

   
  const createCourse = async () => {
    const token1 = userStore.token
    console.log(token1)
const userId = parseJwt(token1).sub
const formattedStartTime = dayjs(newCourse.value.startTime).format('YYYY-MM-DD HH:mm:ss')

console.log(userId)
  createForm.value.validate(async valid => {
    if (!valid) return
    try {
      const params = {
        userId: userId,  // 从登录用户获取
        channelName: newCourse.value.title,
        startTime: formattedStartTime
      }
      const res = await request.post('/rtc/create', null, { params })
      if (res.code === 200) {
        ElMessage.success('创建成功')
        showCreateDialog.value = false
        newCourse.value.title = ''
        newCourse.value.startTime = ''
        fetchCourses()  // 创建后刷新列表
      } else {
        ElMessage.error(res.message || '创建失败')
      }
    } catch (e) {
      ElMessage.error('创建直播课失败')
    }
  })
}


const fetchCourses = async () => {
  try {
    const res = await request.get('/rtc/allchannel')
    console.log(res.message)

    if (res.code === 200) {
      const data = Array.isArray(res.data) ? res.data : []
      courses.value = data.map(item => ({
        id: item.channelId,
        channelName: item.channelName,
        startTime: item.startTime,
        userId: item.userId
      }))
      if (courses.value.length === 0) {
        ElMessage.info('暂无直播课')
      }
    } else {
      ElMessage.warning(res.message || '获取直播课失败')
    }
  } catch (e) {
    ElMessage.error('获取直播课失败')
    console.error(e)
  }
}



onMounted(fetchCourses)

  </script>
  
  <style scoped>
  .live-course-list .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  </style>
  